package com.moresir.validatetools;

import com.moresir.validatetools.common.response.ResponseEnum;
import com.moresir.validatetools.exceptions.BusinessException;
import com.moresir.validatetools.util.HashMapForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FCheck {

    private static FCheck fTest = null;

    private FCheck() {
    }

    public static FCheck getInstance() {
        if (fTest == null)
            fTest = new FCheck();
        return fTest;
    }

    public ExecuteTests test() {
        return new ExecuteTests(this);
    }

    public static class ExecuteTests {

        private FCheck ftest;
        private String nodeName = "默认节点";//defaultTop，标识当前数据节点，报错信息用
        private Map<String, Object> fields = new HashMap<>();
        private Map<String, String> rules = new HashMap<>();

        public ExecuteTests(FCheck ftest) {
            this.ftest = ftest;
        }

        public ExecuteTests rule(String field, String rule, boolean success) {

            rules.put(field, rule);
            return this;
        }

        public ExecuteTests nodeName(String name){
            if(StringUtils.isBlank(name)){
                nodeName = "默认节点";//defaultTop
            } else {
                nodeName = name;
            }
            return this;
        }

        public ExecuteTests rule(Map<String, Object> map){
            map.forEach((k, v)->{
                rule(k, v.toString(), true);
            });
            return this;
        }

        public ExecuteTests field(Map<String, Object> map){
            fields.putAll(map);
            return this;
        }

        public ExecuteTests field(String field, Object value) {
            fields.put(field, value);
            return this;
        }

        public FCheck build() {
            try{
                com.moresir.validatetools.Validator va = new com.moresir.validatetools.Validator(new HashMapForm(fields));
                rules.forEach((k, v) -> {
                    va.addRule(":1 -> :2", k, v);
                });
                Map<String, String> check = va.check();
                check.forEach((key, value) ->{
                    throw new BusinessException(ResponseEnum.VALIDATE_EXCEPTION.getCode(), value);
                });

                return ftest;
            } catch (BusinessException e){
                e.printStackTrace();
                throw new BusinessException(e.getCode(), "入参校验异常-03:节点-" + nodeName + ", " + e.getMessage());
            } catch (Exception e){
                e.printStackTrace();
                throw new BusinessException(ResponseEnum.VALIDATE_EXCEPTION.getCode(), "入参校验异常-03:节点-" + nodeName +  ", " +e.getMessage());
            }
        }
    }
}
